//
//  PPOtherUserCardViewController.m
//  pet
//
//  Created by 陈无忌 on 11/13/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPOtherUserCardViewController.h"
#import "PPOtherUserCenterTableViewController.h"
#import "PPOtherInfoTableViewController.h"

#import "ChatViewController.h"
#import "PPAblumsCollectionViewCell.h"

#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"
#import "PPTopicImage.h"

@interface PPOtherUserCardViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *areaView;
@property (weak, nonatomic) IBOutlet UIView *signatureView;
@property (weak, nonatomic) IBOutlet UIView *ablumView;
@property (weak, nonatomic) IBOutlet UICollectionView *ablumCollectionView;
@property (weak, nonatomic) IBOutlet UIImageView *userAvatar;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (weak, nonatomic) IBOutlet UILabel *signatureLabel;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (strong, nonatomic) NSMutableArray *ablumsArray;
@property (weak, nonatomic) PPSystemConfiguraton *config;

@property (weak, nonatomic) IBOutlet UIButton *followButton;
@property (weak, nonatomic) IBOutlet UIButton *singleChatButton;

@property (strong, nonatomic) UIAlertView *applyAlertView;

@end

@implementation PPOtherUserCardViewController

- (PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return  _config;
}

- (UIAlertView *)applyAlertView
{
    if (!_applyAlertView) {
        _applyAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"跟他打个招呼吧~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_applyAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    }
    return _applyAlertView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //gesture
    UITapGestureRecognizer *imageRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goInfo)];
    self.userAvatar.userInteractionEnabled = YES;
    imageRecognizer.numberOfTouchesRequired = 1;
    imageRecognizer.numberOfTapsRequired = 1;
    [self.userAvatar addGestureRecognizer:imageRecognizer];
    
    UITapGestureRecognizer *viewRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goUserPage)];
    self.ablumView.userInteractionEnabled = YES;
    viewRecognizer.numberOfTouchesRequired = 1;
    viewRecognizer.numberOfTapsRequired = 1;
    [self.ablumView addGestureRecognizer:viewRecognizer];
    
    //viewStyle
    [self viewStyle:self.areaView];
    [self viewStyle:self.signatureView];
    [self viewStyle:self.ablumView];
    
    self.ablumCollectionView.delegate = self;
    self.ablumCollectionView.dataSource = self;
    
    [self.userAvatar setImageWithURL:[PPImageUrl getImageUrl:self.user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.userNameLabel.text = self.user.userName;
    self.areaLabel.text = self.user.address;
    self.signatureLabel.text = self.user.signature;
    //get ablums
    [self getAblum];
    // Do any additional setup after loading the view.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollection View datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.ablumsArray.count >= 3) {
        return 3;
    }else if (self.ablumsArray.count == 0){
        return 1;
    }else{
        return self.ablumsArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPAblumsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PPAblumCell" forIndexPath:indexPath];
    if (self.ablumsArray.count > 0) {
        PPTopicImage *img = [self.ablumsArray objectAtIndex:indexPath.row];
        [cell.ablumImageView setImageWithURL:[PPImageUrl getImageUrl:img.img] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [cell.ablumImageView setContentMode:UIViewContentModeScaleAspectFill];
        [cell.ablumImageView setClipsToBounds:YES];

    }else{
        [cell.ablumImageView setImage:[UIImage imageNamed:@"defaultImage"]];
    }
    return cell;
}

#pragma mark -Custom IBAction

- (IBAction)toChat:(id)sender {
    if ([self checkFriend]) {
        //如果是好友 直接去聊天页面
        NSString *url = [PPAPIList getAPIList].PPQueryConversationByTargetId;
        NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id)};
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                //查询成功 直接得到会话传入
                NSError *err = nil;
                NSDictionary *resultMap = responseObject[@"resultMap"];
                NSDictionary *conversationDic = resultMap[@"conversation"];
                PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:[NSNumber numberWithInt:conversation.isGroup].boolValue];
                
                [conversation.conversation markMessagesAsRead:YES];
                ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
                
                targetVC.myConversation = conversation;
                targetVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:targetVC animated:YES];
                
                
            }else{
                [PPHUD hudShowWithString:@"会话获取失败" andView:self.view];
                //查询失败
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        }];
        
    }else{
        //不是好友 先发送好友请求
        [self.applyAlertView textFieldAtIndex:0].text = [NSString stringWithFormat:@"我是%@",self.config.userInfo.userName];
        [self.applyAlertView show];
    }
    
}

- (IBAction)follow:(id)sender {
    [self checkType];
}

#pragma mark - alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView isEqual:self.applyAlertView]) {
        UITextField *messageTextField = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            NSString *url = [PPAPIList getAPIList].PPSendRequest;
            NSDictionary *params = @{@"sendUserId":@(self.config.userInfo.id),@"targetUserId":@(self.user.id),@"message":messageTextField.text};
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber *processResult = responseObject[@"processResult"];
                if (processResult.boolValue) {
                    [self hudShowWithString:@"请求已发送"];
                }else{
                    [self hudShowWithString:@"请求发送失败"];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self hudShowWithString:@"网络错误"];
            }];
        }
    }
}


#pragma mark - other Method

- (void)hudShowWithString:(NSString *)string
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.labelText = string;
    hud.mode = MBProgressHUDModeText;
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [hud removeFromSuperview];
    }];
}

- (void)viewStyle:(UIView *)view
{
    view.layer.cornerRadius = 8;
    view.layer.borderWidth = 1.0f;
    view.layer.borderColor = [UIColor whiteColor].CGColor;
}

-(void)alertShow :(NSString *)string
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (void)getAblum
{
    NSString *url = [PPAPIList getAPIList].PPGetUserAblums;
    NSDictionary *params = @{@"userId":@(self.user.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //
        NSDictionary *resultMap = responseObject[@"resultMap"];
        self.ablumsArray = [PPTopicImage arrayOfModelsFromDictionaries:resultMap[@"ablumsList"]];
        [self.ablumCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hudShowWithString:@"相册获取失败"];
        //
    }];
}

- (BOOL)checkFriend
{
    for (PPUserInfo *user in self.config.friendArray) {
        if (user.id == self.user.id) {
            return YES;
        }
    }
    return NO;
}

-(void)checkType
{
    NSString *url = [PPAPIList getAPIList].PPIsFollow;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *mapDic = responseObject[@"resultMap"];
        NSNumber *followNum = mapDic[@"followStatus"];
        if (followNum.intValue == 0) {
            [self hudShowWithString:@"已关注该用户"];
        }else if (followNum.intValue == 1){
            NSString *url = [PPAPIList getAPIList].PPFollow;
            NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id),@"type":@(1)};
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
                NSNumber *result = responseObject[@"processResult"];
                if (result.boolValue) {
                    [self hudShowWithString:@"关注成功"];
                }else{
                    [self hudShowWithString:@"关注失败"];
                }
            }failure:^(AFHTTPRequestOperation *operation, NSError *error){
                [self hudShowWithString:@"操作失败"];
            }];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hudShowWithString:@"操作失败"];
    }];
}

- (void)goUserPage
{
    PPOtherUserCenterTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCenterTableViewController"];
    targetVC.user = self.user;
    [self.navigationController pushViewController:targetVC animated:YES];
}


- (void)goInfo
{
    PPOtherInfoTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherInfoTableViewController"];
    targetVC.user = self.user;
    [self.navigationController pushViewController:targetVC animated:YES];
}

@end
